"""聊天服务模块"""

from typing import Dict, List, AsyncGenerator
from core.services.llm_service import stream_chat_completion


class ChatService:
    """聊天服务类"""
    
    def __init__(self):
        self.conversation_history: List[Dict] = []
    
    def add_message(self, role: str, content: str, **kwargs):
        """添加消息到对话历史"""
        message = {
            "role": role,
            "content": content,
            **kwargs
        }
        self.conversation_history.append(message)
    
    def get_conversation_history(self) -> List[Dict]:
        """获取对话历史"""
        return self.conversation_history.copy()
    
    def clear_history(self):
        """清空对话历史"""
        self.conversation_history.clear()
    
    async def stream_chat(self, user_message: str, deep_research: bool = False) -> AsyncGenerator[str, None]:
        """流式聊天"""
        # 添加用户消息
        self.add_message("user", user_message)
        
        # 获取对话历史
        messages = self.get_conversation_history()
        
        # 流式生成回复
        assistant_response = ""
        async for chunk in stream_chat_completion(messages, deep_research):
            assistant_response += chunk
            yield chunk
        
        # 添加助手回复
        self.add_message("assistant", assistant_response, deep_research=deep_research)
    
    def get_last_messages(self, count: int = 10) -> List[Dict]:
        """获取最近的N条消息"""
        return self.conversation_history[-count:] if count > 0 else self.conversation_history


# 全局聊天服务实例
chat_service = ChatService()
